package com.touchX.display
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class AbstractDisplay extends Sprite
	{
		public function AbstractDisplay()
		{
			super();
			addEvent(this, Event.ADDED_TO_STAGE, added);
			addEvent(this, Event.REMOVED_FROM_STAGE, removed);
			//trace("AbstractDisplay");
		}
		protected function removeIfExists(child:DisplayObject,container:DisplayObjectContainer):void{
			if(child && container){
				if(container.contains(child)){
					container.removeChild(child);
				}
			}
		}
		public function dispose():void{
			clearChildren(this);
			if(parent) parent.removeChild(this);
		}
		public function clearChildren(container:DisplayObjectContainer):void{
			for(var i:int=0;i<container.numChildren;i++){
				var child:DisplayObject=container.getChildAt(0);
				if(child is AbstractDisplay){
					AbstractDisplay(child).dispose();	
				}else{
					clearSubChildrer(container);
				}
			}
		}
		
		private function clearSubChildrer(container:DisplayObjectContainer):void{
			for(var i:int=0;i<container.numChildren;i++){
				var child:DisplayObject=container.getChildAt(0);
				if(child is DisplayObjectContainer){
					clearSubChildrer(DisplayObjectContainer(child));
				}else{
					container.removeChild(child);
				}
			}
		}
		
		protected function added(event:Event):void{
			removeEvent(this, Event.ADDED_TO_STAGE, added);
			addEvent(stage, Event.RESIZE, resize);
			resize();
		}
		protected function removed(event:Event):void{
			removeEvent(stage, Event.RESIZE, resize);
		}
		protected function resize(event:Event = null):void{}
		
		protected function addEvent(dispatcher:EventDispatcher, type:String, listener:Function, useCapture:Boolean = true, priority:int=0):void{
			dispatcher.addEventListener(type, listener, false, priority, useCapture);
		}
		protected function removeEvent(dispatcher:EventDispatcher, type:String,listener:Function):void{
			dispatcher.removeEventListener(type, listener);
		}
		
	}
}